package com.atguigu.demo.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor preHandle() 方法执行了");
        // 目标：满足特定的条件，则放行，否则不放行
        // 特定条件：请求参数中携带 monster=peter
        // 1、获取请求参数
        String monster = request.getParameter("monster");

        // 2、判断 monster 是否为 peter
        if ("peter".equals(monster)) {
            // 3、满足条件时：放行
            return true;
        } else {
            // 4、不满足条件时：不放行，并返回响应
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("您的请求中没有携带 monster，请重试！");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor postHandle() 方法执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor afterCompletion() 方法执行了");
    }
}
